<template>
  <div class="wapper">
    <div @click="show = true" class="value">
      {{ text ? text : "请选择" }}
    </div>

    <van-popup
      v-model="show"
      safe-area-inset-bottom
      close-on-popstate
      position="bottom"
      get-container="body"
    >
      <van-empty
        v-if="!loading && columns.length < 1"
        :image="require('@/assets/empty.svg')"
        description="暂无数据"
      />

      <template v-else>
        <div v-show="showSearch" class="search-wapper">
          <van-search
            v-model="searchValue"
            show-action
            placeholder="请输入搜索单位的关键词"
            action-text="返回"
            @cancel="showSearch = false"
            @input="handleSearchInput"
          />

          <van-cell-group>
            <van-cell
              v-for="item in searchList"
              :key="item.id"
              :title="item.name"
              @click="handleCellClick(item)"
            />
          </van-cell-group>
        </div>

        <van-picker
          v-show="!showSearch"
          class="picker-wapper"
          ref="picker"
          value-key="name"
          show-toolbar
          :loading="loading"
          :columns="columns"
          @confirm="onConfirm"
          @cancel="onCancel"
        >
          <template #title>
            <div
              class="van-ellipsis van-picker__title"
              @click="showSearch = true"
            >
              点我搜索单位
              <van-icon name="search" />
            </div>
          </template>
        </van-picker>
      </template>
    </van-popup>
  </div>
</template>

<script>
import { Picker, Popup, Empty, Search, Cell, CellGroup, Icon } from "vant";
import { getGroupDictionarySelect } from "@/api/check";
import { to } from "@/utils";

export default {
  name: "PickerUrgency",
  components: {
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Empty.name]: Empty,
    [Search.name]: Search,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Icon.name]: Icon,
  },
  model: {
    event: "change",
  },
  props: {
    value: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      columns: [],
      show: false,
      loading: false,
      showSearch: false,
      searchValue: "",
      searchList: [],
      text: "",
      token: "",
    };
  },
  computed: {
    valueMirror: {
      get: function () {
        return this.value;
      },
      set: function (val) {
        this.$emit("change", val);
      },
    },
  },
  methods: {
    onConfirm(value, index) {
      const targetItem = this.columns[index[0]].children[index[1]];
      this.valueMirror = targetItem.code;
      this.text = targetItem.name;
      this.$nextTick(() => (this.show = false));
    },
    onCancel() {
      this.show = false;
    },
    async fetchColumns() {
      var params = {
        pageModel: {
          Token: this.token,
          Search: ["UnitCode-2-003,UnitCode-2-006,UnitCode-2-001"],
        },
      };
      this.loading = true;
      const [err, res] = await to(getGroupDictionarySelect(params));
      this.loading = false;
      if (!err) {
        this.columns = Array.isArray(res.Result) ? res.Result : [];
        // this.valueMirror = this.columns[0]?.children[0]?.code || "";
        // this.text = this.columns[0]?.children[0]?.name || "";
      }
    },
    handleSearchInput(val) {
      if (!val) {
        this.searchList = [];
        return;
      }
      let arr = this.columns.reduce((pre, { children }, parentIndex) => {
        return pre.concat(
          Array.isArray(children)
            ? children.map((item, index) => ({ ...item, index, parentIndex }))
            : []
        );
      }, []);
      arr = arr.filter(({ name }) => name.includes(val));
      this.searchList = arr.slice(0, 20);
    },
    handleCellClick(item) {
      this.$refs.picker.setIndexes([item.parentIndex, item.index]);
      this.valueMirror = item.code;
      this.text = item.name;
      this.searchValue = "";
      this.searchList = [];
      this.showSearch = false;
      this.show = false;
    },
  },
  created() {
    this.token = localStorage.getItem("tokenKey");
    this.fetchColumns();
  },
};
</script>

<style lang="less" scoped>
.wapper,
.value {
  width: 100%;
  height: 100%;
  text-align: center;
}

.search-wapper {
  height: 100vh;
  display: flex;
  flex-direction: column;

  & > div:last-of-type {
    flex: 1;
    overflow-y: auto;
  }
}

.picker-wapper {
  /deep/ .van-picker-column:first-of-type {
    flex: 0.5;
  }
}

</style>